package com.zhaojonhy.zhaopangwb.adapter;

import android.app.Activity;
import android.content.Intent;
import android.text.Html;
import android.text.SpannableString;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.zhaojonhy.zhaopangwb.R;
import com.zhaojonhy.zhaopangwb.bean.PicUrls;
import com.zhaojonhy.zhaopangwb.bean.Statuses;
import com.zhaojonhy.zhaopangwb.bean.User;
import com.zhaojonhy.zhaopangwb.ui.ImageBrowserActivity;
import com.zhaojonhy.zhaopangwb.ui.StatusDetailActivity;
import com.zhaojonhy.zhaopangwb.utils.ImageOptHelper;
import com.zhaojonhy.zhaopangwb.utils.ToastUtils;
import com.zhaojonhy.zhaopangwb.ui.UserInfoActivity;
import com.zhaojonhy.zhaopangwb.ui.WriteCommentAcyivity;
import com.zhaojonhy.zhaopangwb.ui.WriteStatusActivity;
import com.zhaojonhy.zhaopangwb.utils.DateUtils;
import com.zhaojonhy.zhaopangwb.utils.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by Administrator on 2016/9/12.
 */
public class StatusAdapter extends BaseAdapter {

    final static String TAG = StatusAdapter.class.getSimpleName() ;

    private Activity context ;
    private List<Statuses> mStatusesList;
    private ImageLoader imageLoader ;

    public StatusAdapter(Activity context,List<Statuses> mStatusesList) {
        this.context = context ;
        this.mStatusesList = mStatusesList;
        imageLoader = ImageLoader.getInstance();
    }

    @Override
    public int getCount() {
        return mStatusesList.size() ;
    }

    @Override
    public Object getItem(int position) {
        return mStatusesList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        Holder holder = null ;
        if( convertView == null){
            holder = new Holder() ;
            convertView = View.inflate(context, R.layout.items_status ,null) ;
            holder.ll_card_content = (LinearLayout)convertView.findViewById(R.id.ll_card_content) ;
            holder.iv_avatar = (ImageView)convertView.findViewById(R.id.iv_avatar) ;
            holder.rl_content = (RelativeLayout)convertView.findViewById(R.id.rl_content) ;
            holder.tv_subhead = (TextView)convertView.findViewById(R.id.tv_subhead) ;
            holder.tv_caption = (TextView)convertView.findViewById(R.id.tv_caption) ;

            holder.tv_content = (TextView)convertView.findViewById(R.id.tv_content) ;
//            holder.wb_view = (WebView) convertView.findViewById(R.id.wb_view) ;

            holder.include_status_image = (FrameLayout)convertView.
                    findViewById(R.id.include_status_image) ;
            holder.gv_images = (GridView)holder.include_status_image.findViewById(R.id.gv_images) ;
            holder.iv_images = (ImageView)holder.include_status_image.findViewById(R.id.iv_image) ;
            holder.tv_pic_flash = (TextView)holder.include_status_image.findViewById(R.id.tv_pic_flash) ;


            holder.include_retweeted_status = (LinearLayout)convertView.
                    findViewById(R.id.include_retweeted_status) ;
            holder.tv_resweeted_content = (TextView)  holder.include_retweeted_status.
                    findViewById(R.id.tv_resweeted_content) ;
            holder.re_wb_view = (WebView) holder.include_retweeted_status.findViewById(R.id.re_wb_view) ;

            holder.include_resweeted_status_image = (FrameLayout) holder.include_retweeted_status.
                    findViewById(R.id.include_retweeted_status_image) ;
            holder.tv_resweeted_gv_images = (GridView) holder.include_resweeted_status_image.
                    findViewById(R.id.gv_images) ;
            holder.tv_resweeted_iv_images = (ImageView) holder.include_resweeted_status_image.
                    findViewById(R.id.iv_image) ;
            holder.tv_resweeted_pic_flash = (TextView) holder.include_resweeted_status_image.
                    findViewById(R.id.tv_pic_flash) ;

            holder.include_bottom_control = (LinearLayout)convertView.
                    findViewById(R.id.include_bottom_control) ;
            holder.ll_share_bottom = (LinearLayout)convertView.
                    findViewById(R.id.ll_share_bottom) ;
            holder.iv_share_bottom = (ImageView)convertView.
                    findViewById(R.id.iv_share_bottom) ;
            holder.tv_share_bottom = (TextView)convertView.
                    findViewById(R.id.tv_share_bottom) ;
            holder.ll_comment_bottom = (LinearLayout)convertView.
                    findViewById(R.id.ll_comment_bottom) ;
            holder.iv_comment_bottom = (ImageView)convertView.
                    findViewById(R.id.iv_comment_bottom) ;
            holder.tv_comment_bottom = (TextView)convertView.
                    findViewById(R.id.tv_comment_bottom) ;
            holder.ll_like_bottom = (LinearLayout)convertView.
                    findViewById(R.id.ll_like_bottom) ;
            holder.iv_like_bottom = (ImageView)convertView.
                    findViewById(R.id.iv_like_bottom) ;
            holder.tv_like_bottom = (TextView)convertView.
                    findViewById(R.id.tv_like_bottom) ;
            convertView.setTag(holder);
        }else {
            holder = (Holder) convertView.getTag();
        }
        //Bind mStatusesList
        final Statuses status =(Statuses)getItem(position) ;
        final User user = status.getUser() ;

        //图片加载
        imageLoader.displayImage(user.getProfile_image_url(),holder.iv_avatar, ImageOptHelper.getAvatarOptions());

//        imageLoader.displayImage(user.getProfile_image_url(),holder.iv_avatar);
        //设置头像
        holder.tv_subhead.setText(user.getName());
        //设置发微博时间和来源
        if( status.getSource().equals("")){
            holder.tv_caption.setText(DateUtils.getShortTime(status.getCreated_at()));
        }else{
            holder.tv_caption.setText(DateUtils.getShortTime(status.getCreated_at())
                    +" 来自 "+ Html.fromHtml(status.getSource()));
            Log.d(TAG,"Html.fromHtm:"+status.getSource()) ;
        }

        //微博正文
        //处理发文内容的特殊文字
        holder.tv_content.setText(StringUtils.getWeiboContent(
                context, holder.tv_content,status.getText()));

        holder.iv_avatar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(context,UserInfoActivity.class) ;
                intent.putExtra("userName",user.getName()) ;
                context.startActivity(intent) ;
            }
        });

        holder.tv_subhead.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(context,UserInfoActivity.class) ;
                intent.putExtra("userName",user.getName()) ;
                context.startActivity(intent) ;
            }
        });

//        Parser parser = new Parser ("http://www.dangdang.com");
//        NodeList list = parser.parse (null);
//        Node node = list.elementAt (0);
//        NodeList sublist = node.getChildren ();
//        System.out.println (sublist.size ());
//
//        if( !TextUtils.isEmpty( vedioUrl(status.getText(),position) )){
//            holder.wb_view.setVisibility(View.VISIBLE);
//            initWebView(holder.wb_view,vedioUrl(status.getText(),position)) ;
//        }else {
//            holder.wb_view.setVisibility(View.GONE);
//        }


        Log.d(TAG,"zhaop--> vedioUrl  position: "+position+ "tv_contentText: " + holder.tv_content.getText() ) ;

//        Log.d(TAG,"zhaop--> vedioUrl  position: "+position+ "  vedioUrl: " + vedioUrl.getVedioUrl() ) ;
//        if(  vedioUrl != null  ){
//            holder.wb_view.loadUrl(vedioUrl);
//            holder.wb_view.setVisibility(View.VISIBLE);
//            //设置可自由缩放网页
//            holder.wb_view.getSettings().setSupportZoom(true);
//            holder.wb_view.getSettings().setBuiltInZoomControls(true);
//            // 如果页面中链接，如果希望点击链接继续在当前browser中响应，
//            // 而不是新开Android的系统browser中响应该链接，必须覆盖webview的WebViewClient对象
//            holder.wb_view.setWebViewClient(new WebViewClient(){
//                @Override
//                public boolean shouldOverrideUrlLoading(WebView view, String url) {
//                //  重写此方法表明点击网页里面的链接还是在当前的webview里跳转，不跳到浏览器那边
//                    view.loadUrl(url);
//                    return true ;
//                }
//            });
//        }

        //设置发微博的图片（判断单图或者多图）
        setImages(position,status,holder.include_status_image,holder.gv_images,holder.iv_images
        ,holder.tv_pic_flash);

        //引用微博部分
        Statuses retweeted_status = status.getRetweeted_status() ;
        if( retweeted_status!= null ){

            //引用正文
            User retUser = retweeted_status.getUser() ;
            holder.include_retweeted_status.setVisibility(View.VISIBLE);
            //处理发文内容的特殊文字
            String resweetedContent ;
            try {
                resweetedContent = "@"+retUser.getName()+":"
                        +retweeted_status.getText() ;
            } catch (NullPointerException e ) {
                resweetedContent = retweeted_status.getText() ;
            }

            holder.tv_resweeted_content.setText(StringUtils.getWeiboContent(
                    context, holder.tv_resweeted_content,resweetedContent));

//            if( !TextUtils.isEmpty( vedioUrl(resweetedContent,position) )){
//                holder.re_wb_view.setVisibility(View.VISIBLE);
//                initWebView(holder.re_wb_view,vedioUrl(resweetedContent,position)) ;
//            }else {
//                holder.re_wb_view.setVisibility(View.GONE);
//            }

            //引用图片
            setImages(position,retweeted_status,holder.include_resweeted_status_image,
                    holder.tv_resweeted_gv_images,holder.tv_resweeted_iv_images,
                    holder.tv_resweeted_pic_flash);
        }else{
            holder.include_retweeted_status.setVisibility(View.GONE);
            Log.d(TAG,"include_retweeted_status-->"+"is Gone") ;
        }
        Log.d(TAG,"include_bottom_control-->"+"reposts_count() :"+ status.getReposts_count()) ;
        Log.d(TAG,"include_bottom_control-->"+"comments_count() :"+ status.getComments_count()) ;
        Log.d(TAG,"include_bottom_control-->"+"attitudes_count() :"+ status.getAttitudes_count()) ;
        holder.tv_share_bottom.setText(status.getReposts_count() == 0 ? "转发"
                : status.getReposts_count()+"");
        holder.tv_comment_bottom.setText(status.getComments_count() == 0 ? "评论"
                : status.getComments_count()+"");
        holder.tv_like_bottom.setText(status.getAttitudes_count() == 0 ? "赞"
                : status.getAttitudes_count()+"");

        holder.ll_card_content.setOnClickListener(new View.OnClickListener() { //整个Item,跳转到详情页
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(context ,StatusDetailActivity.class) ;
                intent.putExtra("status" ,status) ; //可序列化后就可传入
                context.startActivity(intent);
            }
        });

        holder.include_retweeted_status.setOnClickListener(new View.OnClickListener() { //引用微博
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(context ,StatusDetailActivity.class) ;
                intent.putExtra("status" ,status) ;
                context.startActivity(intent);
            }
        });

        holder.ll_share_bottom.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(context ,WriteStatusActivity.class) ;
                intent.putExtra("status" ,status) ;
                intent.putExtra("isRetweet",true ) ;
                context.startActivity(intent);
            }
        });

        holder.ll_comment_bottom.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(status.getComments_count() > 0) { //转到详情页面，并定位到微博的数据
                    Intent intent = new Intent(context, StatusDetailActivity.class);
                    intent.putExtra("status", status);
                    intent.putExtra("scroll2Comment", true); // 跳转到详情页面的评论部分
                    context.startActivity(intent);
                } else { //评论数为0，转到发评论页面
                    Intent intent = new Intent(context, WriteCommentAcyivity.class);
                    intent.putExtra("status", status);
                    context.startActivity(intent);
                }
                ToastUtils.showToast(context, "评个论~", Toast.LENGTH_SHORT);
            }
        });

        holder.ll_like_bottom.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ToastUtils.showToast(context, "点个赞~", Toast.LENGTH_SHORT);
            }
        });

        Log.d(TAG,"mStatusesList：" + mStatusesList.size() ) ;

        return convertView;
    }

    private void setImages(int position ,final Statuses status, FrameLayout imgContainer
            , GridView gridView, ImageView imageView , TextView textView ) {

        textView.setVisibility(View.GONE);

        ArrayList<PicUrls> pic_urls = status.getPic_urls() ;
        String bmiddle_pic = status.getBmiddle_pic();
        if(pic_urls != null){
            Log.d(TAG,"pic_urls :"+ pic_urls.toString()) ;
        }

        if( !TextUtils.isEmpty(bmiddle_pic)) {
            Log.d(TAG,"bmiddle_pic :"+bmiddle_pic.lastIndexOf(".") ) ;
            Log.d(TAG,"bmiddle_pic :"+"position :"+ position +bmiddle_pic.
                    substring(bmiddle_pic.lastIndexOf(".")+1)  ) ;
        }

        if ( pic_urls!=null && pic_urls.size() != 0  ) {
            Log.d(TAG,"wangkq--> setImages  position: "+position+ "  pic_urls: " + pic_urls.size()) ;
            imgContainer.setVisibility(View.VISIBLE);
            if ( pic_urls.size() > 1 ) { //多图
                gridView.setVisibility(View.VISIBLE);
                imageView.setVisibility(View.GONE);
                StatusGridImgsAdapter gvAdapter = new StatusGridImgsAdapter(context,pic_urls) ;
                gridView.setAdapter(gvAdapter);
                //点击多图事件
                gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        Intent intent = new Intent(context, ImageBrowserActivity.class) ;
                        intent.putExtra("status" ,status) ;
                        intent.putExtra("position" ,position) ;
                        context.startActivity(intent) ;
                    }
                });

            }else{
                textView.setVisibility(View.GONE);

                gridView.setVisibility(View.GONE);
                imageView.setVisibility(View.VISIBLE);
                if((bmiddle_pic.
                        substring(bmiddle_pic.lastIndexOf(".")+1 ) ).equals("gif")) {
                    textView.setVisibility(View.VISIBLE);
                }else {
                    textView.setVisibility(View.GONE);
                }

                Log.d(TAG,"wangkqAAA-->  pic: " +bmiddle_pic) ;

                imageLoader.displayImage(bmiddle_pic,imageView);
                //点击单图事件
                imageView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(context, ImageBrowserActivity.class) ;
                        intent.putExtra("status" ,status) ;
                        context.startActivity(intent) ;
                    }
                });
            }
        }else{
            Log.d(TAG,"wangkq--> setImages position:"+position+ " pic_urls === 0") ;
            imgContainer.setVisibility(View.GONE);
        }
    }

    public class Holder {
        private LinearLayout ll_card_content ;
        private TextView tv_content ;
        private FrameLayout include_status_image ;
        private LinearLayout include_retweeted_status ;
        private LinearLayout include_bottom_control ;

        private ImageView iv_avatar;
        private RelativeLayout rl_content;
        private WebView wb_view;
        private TextView tv_subhead;
        private TextView tv_caption;

        private GridView gv_images ;
        private ImageView iv_images;
        private TextView tv_pic_flash ;

        private TextView tv_resweeted_content ;
        private WebView re_wb_view;
        private FrameLayout include_resweeted_status_image ;
        private GridView tv_resweeted_gv_images ;
        private ImageView tv_resweeted_iv_images;
        private TextView tv_resweeted_pic_flash ;

        private LinearLayout ll_share_bottom;
        private ImageView iv_share_bottom;
        private TextView tv_share_bottom;
        private LinearLayout ll_comment_bottom;
        private ImageView iv_comment_bottom;
        private TextView tv_comment_bottom;
        private LinearLayout ll_like_bottom;
        private ImageView iv_like_bottom;
        private TextView tv_like_bottom;
    }

    private String vedioUrl(String source ,int position) {
        String vedioUrl = null ;
        //微博视频
        String regex =
                "(http|ftp|https):\\/\\/[\\w\\-_]+(\\.[\\w\\-_]+)+([\\w\\-\\.,@?^=%&amp;:/~\\+#]*[\\w\\-\\@?^=%&amp;/~\\+#])?" ;

        SpannableString spannableString = new SpannableString(source) ;
        Log.d(TAG,"content "+source) ;
        // 正则匹配，传入正则规则和原字符创
        Pattern pattern = Pattern.compile(regex) ;
        Matcher matcher = pattern.matcher(spannableString) ;


        //循环遍历整个字符串
        while (matcher.find()) {
            //返回匹配到的子字符串
            vedioUrl = matcher.group() ;
            if( vedioUrl != null ) {
                Log.d(TAG,"zhaop--> vedioUrl  position: "+position+ "vedioStr: " + vedioUrl ) ;
            }
        }
        return vedioUrl ;
    }

    private void initWebView(WebView webView ,String url){
        final WebSettings wSettings ;
        //获取WebSettings对象
        wSettings=webView.getSettings();
        //启用支持视窗meta标记（可实现双击缩放）
        wSettings.setUseWideViewPort(true);
        //以缩略图模式加载页面
        wSettings.setLoadWithOverviewMode(true);
        //设置js可以直接打开窗口，如window.open()，默认为false
        wSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        //启用JavaScript支持
        wSettings.setJavaScriptEnabled(true);
        //设置将接收各种通知和请求的WebViewClient（在WebView加载所有的链接）
        webView.loadUrl(url);
    }

}
